package com.gupaoedu.demo.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * <p>
 *
 * </p>
 *
 * @author Nicky
 * @since 2019-07-19
 */
public class ServerSocketDemo {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;

        try {
            //服务端一定需要监听一个端口
            serverSocket = new ServerSocket(8080);
            Socket socket = serverSocket.accept(); //接收客户的连接，阻塞
            //输入流
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //输出流
            PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
            System.out.println("client: " + bufferedReader.readLine());
            //从控制台拿到数据
            BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
            String readline = sin.readLine();
            while (!readline.equals("bye")){
                //写回到客户端
                printWriter.println(readline);
                printWriter.flush();
                //读取客户端传过来的数据
                System.out.println("client: " +  bufferedReader.readLine());
                //重新读取控制台数据
                readline = sin.readLine();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                if(serverSocket != null){
                    serverSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
}
